package com.softcits.sb01.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dac
 *
 */
@WebServlet(urlPatterns="/register")
public class RegisterServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("Register page....");

        if(req.getSession().getId() != null && req.getServletContext().getAttribute(req.getSession().getId()) != null){
            User user1 = (User) req.getServletContext().getAttribute(req.getSession().getId());
            System.out.println("username: " +  user1.getUsername());
            System.out.println("password: " +  user1.getPassword());
            System.out.println("mobile: " +  user1.getMobile());
            req.getServletContext().removeAttribute(req.getSession().getId());
        }

        req.getRequestDispatcher("/reg/register.html").forward(req, resp);
        //resp.sendRedirect("/reg/register.html");
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");

        String password = req.getParameter("password");
        String mobile = req.getParameter("mobile");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setMobile(mobile);
        PrintWriter pw = resp.getWriter();
        pw.write("<html><body>");
        pw.write(String.format("<script>alert('username:' + '%s' + ' password: ' + '%s' );</script>", username, password));
        pw.write("</body></html>");
        req.getServletContext().setAttribute(req.getSession().getId(),user);
        User user1 = (User) req.getServletContext().getAttribute(req.getSession().getId());
        System.out.println("username: " +  user1.getUsername());
        System.out.println("password: " +  user1.getPassword());
        System.out.println("mobile: " +  user1.getMobile());


    }

}
